<!-- 样方返青率 -->
<template>
	<view class="container">
		<view class="example">
			<!-- 基础用法，不包含校验规则 -->
			<uni-forms ref="baseForm" class="form-box" :model="yddata" labelWidth="125px">
				<uni-forms-item label="越冬前存活基数">
					<uni-easyinput v-model="yddata.fqydqchjs" :disabled="isview" placeholder="请输入 株" />
				</uni-forms-item>
				<uni-forms-item label="越冬后存活基数">
					<uni-easyinput v-model="yddata.fqydhchjs" :disabled="isview" placeholder="请输入 株" />
				</uni-forms-item>
				<uni-forms-item label="越冬率">
					<uni-easyinput v-model="yddata.fqydl" :disabled="isview" placeholder="请输入 %" />
				</uni-forms-item>
				<uni-forms-item label="总盖度">
					<uni-easyinput v-model="yddata.fqzgd" :disabled="isview" placeholder="请输入" />
				</uni-forms-item>
				<uni-forms-item label="植被成活面积">
					<uni-easyinput v-model="yddata.fqzbchmj" :disabled="isview" placeholder="请输入" />
				</uni-forms-item>


				<uni-forms-item label="照片" class="uni-list list-pd">
					<view class="uni-list-cell cell-pd">
						<view class="uni-uploader">
							<view class="uni-uploader-body">
								<view class="uni-uploader__files">
									<block v-for="(image,index) in imageList" :key="index">
										<view class="uni-uploader__file">
											<image class="uni-uploader__img" :src="image" :data-src="image"
												@tap="previewImage"></image>
										</view>
									</block>
									<view class="uni-uploader__input-box">
										<view class="uni-uploader__input" @tap="chooseImage"></view>
									</view>
								</view>
							</view>
						</view>
					</view>
				</uni-forms-item>



			</uni-forms>
			<button type="primary" @click="submit('valiForm')">{{title}}</button>

		</view>


	</view>
</template>

<script>
	import {
		addOrUpdateYf
	} from '@/api/system.js'
	import {
		getInfo,
		setInfo
	} from '@/core/unicommon/storyageInfo.js'
	import {
		saveImage,
		uploadImage
	} from '@/core/file/File.js'
	export default {
		data() {
			return {
				title: "提交",
				sourceTypeIndex: 2,
				sourceType: ['拍照', '相册', '拍照或相册'],
				sizeTypeIndex: 2,
				sizeType: ['压缩', '原图', '压缩或原图'],
				countIndex: 8,
				count: [1, 2, 3, 4, 5, 6, 7, 8, 9],
				isview: true,
				// 基础表单数据
				yddata: {
					"altitude": "",
					"createTime": "2023-12-06T13:41:52.517Z",
					"fqqyfzp": "",
					"fqyszwmc": "",
					"fqzbgd": "",
					"fqzbmc": "",
					"fqzbzs": "",
					"fqzzpjgd": "",
					"humidness": "",
					"khyfzp": "",
					"khyszwmc": "",
					"khzbgd": "",
					"khzwmc": "",
					"khzwpjgd": "",
					"khzwzs": "",
					"lat": "",
					"lon": "",
					"sqyfzp": "",
					"surveyType": "",
					"temperature": "",
					"updateTime": "2023-12-06T13:41:52.517Z",
					"ydNumber": "",
					"yfNumber": (new Date()).getFullYear() + "-",
					"zbfqbfl": "",
					"zbgd": "",
					"zbkhbfl": "",
					"zbzgd": "",
					yfzp: ""
				},
				imageList: [],


				// 校验表单数据
				valiFormData: {
					name: '',
					age: '',
					introduction: '',
				},
				// 校验规则
				rules: {
					name: {
						rules: [{
							required: true,
							errorMessage: '姓名不能为空'
						}]
					},
					age: {
						rules: [{
							required: true,
							errorMessage: '年龄不能为空'
						}, {
							format: 'number',
							errorMessage: '年龄只能输入数字'
						}]
					}
				},

			}
		},
		computed: {

		},
		onLoad(e) {
			if (e && e.data) {
				let data = JSON.parse(decodeURIComponent(e.data))

				getInfo("userdata").then(res => {
					let udata = res.data;
					this.yddata = res.data.yf.find(t => t.ydNumber == data.ydNumber && t.yfNumber == data.yfNumber)
					this.isview = true
					this.title = "编辑"


					let files = udata.files
					this.imageList = []
					if (this.yddata.yfzp) {
						let sqzp = JSON.parse(this.yddata.yfzp)
						for (const zp of sqzp) {
							let localzp = files.find(t => t.type == 'yf' && t.uid == zp.uid)
							if (localzp) {
								this.imageList.push(localzp.localurl)
							}
						}
					}

				})
			} else {
				uni.showToast({
					title: `未获取到相关样方信息`
				})
			}
			this.getNetWork()

		},
		onReady() {
			this.getNetWork()
		},
		methods: {
			getNetWork() {
				let that = this
				uni.getNetworkType({
					success: res => {
						if (res.networkType === 'none') {
							that.network = false
						} else {
							that.network = true
						}
					}
				})
			},
			isFullImg() {
				return new Promise((res) => {
					uni.showModal({
						content: "已经有9张图片了,是否清空现有图片？",
						success: (e) => {
							if (e.confirm) {
								this.imageList = [];
								res(true);
							} else {
								res(false)
							}
						},
						fail: () => {
							res(false)
						}
					})
				})
			},
			async chooseImage() {
				if (this.title != '提交') {
					return
				}
				// #ifdef APP-PLUS
				// TODO 选择相机或相册时 需要弹出actionsheet，目前无法获得是相机还是相册，在失败回调中处理
				if (this.sourceTypeIndex !== 2) {
					let status = await this.checkPermission();
					if (status !== 1) {
						return;
					}
				}
				// #endif

				if (this.imageList.length === 9) {
					let isContinue = await this.isFullImg();
					console.log("是否继续?", isContinue);
					if (!isContinue) {
						return;
					}
				}
				uni.chooseImage({
					sourceType: ['camera', 'album'],

					count: this.imageList.length + this.count[this.countIndex] > 9 ? 9 - this.imageList
						.length : this.count[this.countIndex],
					success: (res) => {
						this.imageList = this.imageList.concat(res.tempFilePaths);
					},
					fail: (err) => {
						console.log("err: ", err);
						// #ifdef APP-PLUS
						if (err['code'] && err.code !== 0 && this.sourceTypeIndex === 2) {
							this.checkPermission(err.code);
						}
						// #endif
						// #ifdef MP
						if (err.errMsg.indexOf('cancel') !== '-1') {
							return;
						}
						uni.getSetting({
							success: (res) => {
								let authStatus = false;
								switch (this.sourceTypeIndex) {
									case 0:
										authStatus = res.authSetting['scope.camera'];
										break;
									case 1:
										authStatus = res.authSetting['scope.album'];
										break;
									case 2:
										authStatus = res.authSetting['scope.album'] && res
											.authSetting['scope.camera'];
										break;
									default:
										break;
								}
								if (!authStatus) {
									uni.showModal({
										title: '授权失败',
										content: 'Hello uni-app需要从您的相机或相册获取图片，请在设置界面打开相关权限',
										success: (res) => {
											if (res.confirm) {
												uni.openSetting()
											}
										}
									})
								}
							}
						})
						// #endif
					}
				})
			},
			async checkPermission(code) {
				console.log("code", code)
				let type = code ? code - 1 : this.sourceTypeIndex;
				let status = permision.isIOS ? await permision.requestIOS(sourceType[type][0]) :
					await permision.requestAndroid(type === 0 ? 'android.permission.CAMERA' :
						'android.permission.READ_EXTERNAL_STORAGE');

				if (status === null || status === 1) {
					status = 1;
				} else {
					uni.showModal({
						content: "没有开启权限",
						confirmText: "设置",
						success: function(res) {
							if (res.confirm) {
								permision.gotoAppSetting();
							}
						}
					})
				}

				return status;
			},
			previewImage: function(e) {
				var current = e.target.dataset.src
				uni.previewImage({
					current: current,
					urls: this.imageList
				})
			},



			submit(ref) {
				if (this.title == "提交") {
					uni.showLoading({
						title: "提交中",
						mask: true,
						icon: 'loading',
					})
					if (this.network) {
						this.yddata.action = 'none'
					} else {
						if (this.yddata.action == 'none') {
							this.yddata.action = 'edit'
						}
					}
					this.saveLocal().then(res => {

						if (this.network) {
							addOrUpdateYf(this.yddata).then(res => {
								uni.hideLoading()
								uni.showToast({
									title: '保存成功',
									icon: 'checkmarkempty'
								})
							})
						} else {
							uni.hideLoading()
							uni.showToast({
								title: '无网络,数据缓存成功',
								icon: 'checkmarkempty'
							})
						}
					})
					this.title = "编辑"
					this.submited = true

				} else {
					this.title = "提交"
					this.isview = false
				}
			},
			async saveLocal() {

				let userdatares = await getInfo("userdata")
				let userdata = userdatares.data
				let that = this
				let peakPeriodzp = []
				for (const img of this.imageList) {
					let saveres = await saveImage(img)
					let upimages = {}
					if (that.network) {
						let res = await uploadImage(saveres.savedFilePath)
						if (res) {
							upimages = JSON.parse(res).data || {}
						}
					}
					let imgInfo = {
						name: '返青率调查',
						uid: upimages.name || (new Date()).getTime(),
						url: upimages.url || null,
						localurl: saveres.savedFilePath,
						id: (new Date()).getTime(),
						action: "edit",
						type: 'yf',
						ydNumber: that.yddata.ydNumber,
						yfNumber: that.yddata.yfNumber
					}
					peakPeriodzp.push(imgInfo)
				}
				userdata.files = userdata.files.concat(peakPeriodzp)
				this.yddata.yfzp = JSON.stringify(peakPeriodzp)


				let yf = userdata.yf
				let index = yf.findIndex(t => t.id == this.yddata.id)
				yf[index] = this.yddata

				userdata.yf = yf

				await setInfo("userdata", userdata)
			}


		}
	}
</script>

<style lang="scss" scoped>
	.container {
		position: absolute;
		width: 100vw;
		height: 100vh;

	}

	.example {
		position: absolute;
		width: 100%;
		height: 100vh;
		overflow-y: auto;

		background-color: #fff;
	}

	.form-box {
		padding: 15px;
	}

	.segmented-control {
		margin-bottom: 15px;
	}




	.button {
		display: flex;
		align-items: center;
		height: 35px;
		line-height: 35px;
		margin-left: 10px;
	}

	.totopindex {
		// width: 100%;
		padding: 10rpx;
		margin: 5rpx;
		height: 80rpx;
		border: 1px solid #ccc;

		.btns {
			float: left;
			text-align: right;
			width: 120rpx;
			float: right;
			line-height: 76rpx;
			color: #00aaff;
			text-decoration: underline;

		}
	}
</style>